#include "head_s.h"

int rm(const user_t* status, const portocol_t* portocol, int net_fd,MYSQL*mysql)
{
    char buf1[1024]={0};
    char buf2[1024]={0};
    char back[10]={0};
    int len = strlen(status->arg);
    if(len ==0){
        back[0]='1';
        send(net_fd,back,sizeof(back),MSG_NOSIGNAL);
        return 0;
    }
    sprintf(buf1,"select id from user_info where name='%s'", status->user_name);
    //拼接语句buf1根据用户名查找用户id


    mysql_query(mysql, buf1);//执行数据库指令
    MYSQL_RES * res =mysql_store_result(mysql);
    MYSQL_ROW row;
    //获取一行数据
    row = mysql_fetch_row(res);


    int id= atoi(row[0]);
    //获取id完成

    mysql_free_result(res);//释放结果集

    char path_last[512]={0};
    sprintf(path_last,"%s%s",status->path,status->arg);
    //拼接路径和参数
    sprintf(buf2,"select exist_flag from file_info where user_id = %d and file_path = '%s'",id,path_last);
    //拼接语句buf2根据id和路径查找标识符
    mysql_query(mysql, buf2);//运行数据库指令
    MYSQL_RES * res_1 =mysql_store_result(mysql);
    if(res_1==NULL){
        back[0]= '1';
        send(net_fd,back,sizeof(back),MSG_NOSIGNAL);
        return 0;
    }
    if(mysql_num_rows(res_1) <=0){
        back[0]= '1';
        LOG_WRITE(LOG_ERROR, "失败，未找到数据");
        send(net_fd,back,sizeof(back),MSG_NOSIGNAL);
        //找不到对应文件or文件夹返回1删除失败
        return 0;
    }else{
        MYSQL_ROW row_1;
        row_1 = mysql_fetch_row(res_1);
        int flag = atoi(row_1[0]);
        mysql_free_result(res_1);//释放结果集
        if(flag==0){
            char buf3[1024]={0};
            char type[1024]={0};
            sprintf(type,"select file_type from file_info where user_id = %d and file_path = '%s'",id,path_last);
            mysql_query(mysql, type);//运行数据库指令
            MYSQL_RES * res_2 =mysql_store_result(mysql);
            MYSQL_ROW row_2;
            row_2 = mysql_fetch_row(res_2);
            //获取一行数据
            int file_type= atoi(row_2[0]);
            //获取文件id完成
            mysql_free_result(res_2);//释放结果集




            if(file_type==1){
                sprintf(buf3,"update file_info set exist_flag = 1 where file_path like '%s/%%' and exist_flag = 0 and user_id = %d" ,path_last,id);
                //拼接修改方法,将所有的path_last的儿子删除
                LOG_WRITE(LOG_INFO, "成功进入删除所有下属文件,删除指令为:%s", buf3);
                mysql_query(mysql, buf3);
            }
            char buf4[1024]={0};
            sprintf(buf4,"update file_info set exist_flag = 1 where file_path = '%s' and exist_flag = 0 and user_id = %d" ,path_last,id);
            //拼接修改方法,删除文件
            LOG_WRITE(LOG_INFO, "成功进入删除所有下属文件,删除指令为:%s", buf4);
            back[0]= '0';

            mysql_query(mysql, buf4);
            send(net_fd,back,sizeof(back),MSG_NOSIGNAL);
            return 0;
        }else{
            LOG_WRITE(LOG_ERROR, "失败,数据为1");
            back[0]='1';
            send(net_fd,back,sizeof(back),MSG_NOSIGNAL);
            //找不到对应文件or文件夹返回1删除失败
            return 0;
        }
    }
    return 0;
}

